package com.exteam.common.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;

/**
 * Created by jianan on 2015/6/9.
 * 文件工具
 */
public class FileUtils {

    public static final int SIZE_MB = 1 * 1024 * 1024;
    public static final int SIZE_KB = 1 * 1024;

    public static boolean deleteFile(final File file) {
        if (file == null)
            return false;
        if (file.exists()) { // 判断文件是否存在
            if (file.isFile()) { // 判断是否是文件
                return file.delete();
            } else if (file.isDirectory()) { // 否则如果它是一个目录
                File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
                if (files != null) {
                    for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                        if (deleteFile(files[i]) == false) {// 把每个文件用这个方法进行递归
                            return false;
                        }
                    }
                }
            }
            return file.delete();
        }
        return false;
    }

    public static File saveBitmapToFile(Bitmap bitmap, File path, String pre, String suf) {
        File file = null;
        try {
            file = File.createTempFile(pre, suf, path);
            OutputStream outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
            outStream.flush();
            outStream.close();

        } catch (FileNotFoundException e) {
            CommLogger.d(e.toString());
        } catch (IOException e) {
            CommLogger.d(e.toString());
        }
        return file;
    }

    // 通过ContentResoler得到图片资源，并把其存到缓存目录
    public static File getFileByUri(Context ctx, Uri fileUri, File path, String pre, String suf) {

        File localFile = null;
        try {
            InputStream stream = ctx.getContentResolver().openInputStream(fileUri);
            localFile = FileUtils.saveStreamToFile(stream, path, pre, suf);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            CommLogger.d("getFileByUri" + e.toString());
        }
        return localFile;
    }

    // 通过ContentResoler得到图片资源，并把其存到缓存目录
    public static File getFileByUri(Context ctx, Uri fileUri, File localFile) {

        // File localFile = new File(path,CommUtils.md5(fileUri.toString()));
        CommLogger.d("localFile:" + localFile.getAbsolutePath());
        if (localFile.isFile() && localFile.exists()) {
            return localFile;
        }
        try {
            InputStream stream = ctx.getContentResolver().openInputStream(fileUri);
            localFile = FileUtils.saveStreamToFile(stream, localFile);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            CommLogger.d("getFileByUri" + e.toString());
        }
        return localFile;
    }

    // 根据流生成一个文件
    public static File saveStreamToFile(InputStream stream, File path, String pre, String suf) {
        File file = null;
        try {
            file = File.createTempFile(pre, suf, path);

            OutputStream outStream = new FileOutputStream(file);
            byte[] bs = new byte[100 * 1024];
            while (stream.read(bs) != -1) {
                outStream.write(bs);
                outStream.flush();
            }
            outStream.close();

        } catch (FileNotFoundException e) {
            CommLogger.d(e.toString());
        } catch (IOException e) {
            CommLogger.d(e.toString());
        }
        return file;
    }

    // 根据流生成一个文件
    public static File saveStreamToFile(InputStream stream, File file) {
        try {
            OutputStream outStream = new FileOutputStream(file);
            byte[] bs = new byte[stream.available()];
            while (stream.read(bs) != -1) {
                outStream.write(bs);
                outStream.flush();
            }
            outStream.close();
        } catch (FileNotFoundException e) {
            CommLogger.d(e.toString());
        } catch (IOException e) {
            CommLogger.d(e.toString());
        }
        return file;
    }

    // 根据字符串生成一个文件
    public static File saveContentToFile(String content, File path, String pre, String suf) {
        File file = null;
        try {
            file = File.createTempFile(pre, suf, path);

            OutputStream outStream = new FileOutputStream(file);
            outStream.write(content.getBytes());
            outStream.flush();
            outStream.close();

        } catch (FileNotFoundException e) {
            CommLogger.d(e.toString());
        } catch (IOException e) {
            CommLogger.d(e.toString());
        }
        return file;
    }

    // 根据字符串生成一个文件
    public static void saveContentToFile(String content, File file) {
        try {
            ByteArrayInputStream stream = new ByteArrayInputStream(content.getBytes());
            OutputStream outStream = new FileOutputStream(file);

            byte[] bs = new byte[stream.available()];
            while (stream.read(bs) != -1) {
                outStream.write(bs);
                outStream.flush();
            }
            outStream.close();

        } catch (FileNotFoundException e) {
            CommLogger.d(e.toString());
        } catch (IOException e) {
            CommLogger.d(e.toString());
        }

    }

    /**
     * 获取文件大小MB
     *
     * @return
     */
    public static int getFileSize(File file, int type) {
        return (int) (file.length() / type);
    }

    /**
     * 获取文件目录
     *
     * @return
     */
    public static File getFile(String path) {
        if (!isExistExternalStore()) {
            //ToastUtil.showMessage(R.string.media_ejected);
            return null;
        }

        File directory = new File(path);
        if (!directory.exists() && !directory.mkdirs()) {
            //ToastUtil.showMessage("Path to file could not be created");
            return null;
        }

        return directory;
    }

    /**
     * 获取文件内容
     *
     * @param filePath
     * @return
     */

    public static String getFileContent(String filePath) {
        String fileContent = "";
        try {
            //String path = FileAccessor.getExternalStorePath()+"/test/";
            File fl = new File(filePath);
            FileInputStream fis = new FileInputStream(fl);
            byte[] bs = new byte[fis.available()];
            fis.read(bs);
            fileContent = new String(bs);
            fis.close();

        } catch (Exception e) {
            CommLogger.d("read file err :e:" + e.toString());
        }
        return fileContent;
    }

    /**
     * 获取文件名
     *
     * @param pathName
     * @return
     */
    public static String getFileName(String pathName) {

        int start = pathName.lastIndexOf("/");
        if (start != -1) {
            return pathName.substring(start + 1, pathName.length());
        }
        return pathName;

    }

    /**
     * 外置存储卡的路径
     *
     * @return
     */
    public static String getExternalStorePath() {
        if (isExistExternalStore()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        return null;
    }

    /**
     * 是否有外存卡
     *
     * @return
     */
    public static boolean isExistExternalStore() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * /data/data/com.ECSDK_Demo.bluetooth/files
     *
     * @return
     */
    public static String getAppContextPath(Context context) {

        return context.getFilesDir().getAbsolutePath();
    }


    /**
     * @param fileName
     * @return
     */
    public static String getSecondLevelDirectory(String fileName) {
        if (TextUtils.isEmpty(fileName) || fileName.length() < 4) {
            return null;
        }

        String sub1 = fileName.substring(0, 2);
        String sub2 = fileName.substring(2, 4);
        return sub1 + File.separator + sub2;
    }


    public static void fileChannelCopy(File s, File t) {

        FileInputStream fi = null;

        FileOutputStream fo = null;

        FileChannel in = null;

        FileChannel out = null;

        try {

            fi = new FileInputStream(s);

            fo = new FileOutputStream(t);

            in = fi.getChannel();//得到对应的文件通道

            out = fo.getChannel();//得到对应的文件通道

            in.transferTo(0, in.size(), out);//连接两个通道，并且从in通道读取，然后写入out通道

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                fi.close();

                in.close();

                fo.close();

                out.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

}
